package com.lay.http.core;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Administrator on 2019-11-18.
 */

public class UploadResponse extends ResponseBody {

    @Override
    public void handle(InputStream inputStream, ResponseBody.ProcessListener listener) {
        try {
            final int size = 1024 * 100;
            byte[] buffer = new byte[size];
            int length = 0;
            int l = 0;
            int offset = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            boolean result = true;
            while ((l = inputStream.read(buffer, offset, size - offset)) != -1) {
                if(result){
                    if (listener != null) {
                        length += l;
                        offset += l;
                        if(offset >= size) {
                            byte[] data = new byte[offset];
                            System.arraycopy(buffer, 0, data, 0, offset);
                            result = listener.onProcess(data, length);
                            offset = 0;
                        }
                    } else {
                        result = false;
                    }
                }
                if(!result) {
                    bos.write(buffer, offset, l);
                    offset += l;
                }
            }
            if(result) {
                if(offset != 0){
                    byte[] data = new byte[size];
                    System.arraycopy(buffer, 0, data, 0, offset);
                    listener.onProcess(data, length);
                }
            } else {
                setData(bos.toByteArray());
            }
            bos.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
